import { exec } from 'child_process';
import * as fs from 'node:fs';

import { select } from '@inquirer/prompts';
import { log as logg } from 'crawlee';

/** 选择将要执行脚本 */
const answer = await select({
    message: '选择执行脚本',
    pageSize: 10,
    theme: {
        prefix: '🤖',
        icon: {
            cursor: '💮',
        },
    },
    choices: fs
        .readdirSync('src/examples')
        .sort((a, b) => {
            const reg = /^(\d+)/; // 匹配字符串中的数字部分
            const numA = (reg.exec(a) as any)[1]; // 提取a中的数字部分
            const numB = (reg.exec(b) as any)[1]; // 提取b中的数字部分
            return numA - numB; // 从小到大排序
        })
        .map((m) => ({ name: m, value: m })),
});
logg.info('命令执行中。。。');
/** 将要执行的 cmd 命令 */
let command = '';
switch (process.env.npm_lifecycle_event) {
    case 'dev':
        command = `npx tsx src/examples/${answer}`;
        break;
    case 'prod':
        command = `node dist/examples/${answer}`;
        break;
    default:
        break;
}

/** 执行的 cmd 命令 */
exec(command, (error, stdout, stderr) => {
    if (error) {
        logg.error('执行命令失败：', error);
        return;
    }
    if (stderr) {
        logg.error(`执行命令失败：${stderr}`);
        return;
    }
    logg.info(`执行命令成功：${stdout}`);
});
